package com.ruoyi;

import com.ruoyi.charge.common.GlobalConstant;
import com.ruoyi.charge.domain.ChargingStation;
import com.ruoyi.charge.service.IChargingStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

//把数据库中的数据写入到redis，Tomcat启动时执行
@Component
public class InitApplication {
    @Autowired
    IChargingStationService iChargingStationService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostConstruct//方法在tomcat启动时执行，由框架调用，没有参数，没有返回值
    public void readStationWriteToRedis() {
        System.out.println("readStationWriteToRedis");
        //读取charging数据库中charging_station表中的数据
        //参数是用来生成查询条件的，null表示没有条件，就是查询所有数据
        List<ChargingStation> stationList =
                iChargingStationService.selectChargingStationList(null);
        System.out.println(stationList);
        //org.springframework.data.geo.Point;
        HashMap<String, Point> hashMap = new HashMap<>();
        BoundHashOperations boundHashOperations =
                redisTemplate.boundHashOps(GlobalConstant.STATION_DETAIL_HASH);
        //Long add(Map<M,Point> memberCoordinateMap)
        BoundGeoOperations boundGeoOperations =
                redisTemplate.boundGeoOps(GlobalConstant.STATION_GEO_ZSET);
        //遍历所有充电站，把数据放到放到zset
        for (ChargingStation chargingStation : stationList) {
            //得到充电站编号
            String id = chargingStation.getId().toString();
            //得到充电站的经度，纬度，封装成point
            double longitude =
                    Double.parseDouble(chargingStation.getStationLng().toString());//经度
            double latitude =
                    Double.parseDouble(chargingStation.getStationLat().toString());//纬度
            Point stationPosition = new Point(longitude, latitude);
            //往hashMap中添加一个充电站信息，作为value，key为stationGeoZset类型为zset
            hashMap.put(id, stationPosition);
            //把充电站详情放到hash中，作为value，key为stationDetailHash类型为hash,
            boundHashOperations.put(id, chargingStation);
        }
        boundGeoOperations.add(hashMap);//一次性把所有充电站写入redis
    }
}
